/*
 *  Copyright 2019-2023 oyun
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.oyun.modules.medicine.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oyun.modules.medicine.domain.Hospital;
import com.oyun.modules.medicine.domain.HpPicture;
import com.oyun.modules.medicine.domain.vo.HospitalQueryCriteria;
import com.oyun.modules.medicine.mapper.HospitalMapper;
import com.oyun.modules.medicine.mapper.HpPictureMapper;
import com.oyun.modules.medicine.service.HospitalService;
import com.oyun.segment.convert.itmd.IntermediateCodeUtils;
import com.oyun.utils.FileUtil;
import com.oyun.utils.PageResult;
import com.oyun.utils.PageUtil;
import com.oyun.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

/**
 * @author aoyun
 * @description 服务实现
 * @date 2024-04-25
 **/
@Service
@RequiredArgsConstructor
public class HospitalServiceImpl extends ServiceImpl<HospitalMapper, Hospital> implements HospitalService {

    @Value("${file.windows.path}")
    private String path;

    private final HospitalMapper hospitalMapper;

    private final HpPictureMapper hpPictureMapper;

    @Override
    public PageResult<Hospital> queryAll(HospitalQueryCriteria criteria, Page<Object> page) {
        if (StringUtils.isNotEmpty(criteria.getName())) {
            criteria.setReplaceAll(IntermediateCodeUtils.mn2Code(criteria.getName()).replaceAll("-", " -"));
        }
        IPage<Hospital> all = hospitalMapper.findAll(criteria, page);
        List<Hospital> list = all.getRecords();
        for (Hospital hospital : list) {
            LambdaQueryWrapper<HpPicture> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(hospital.getId() != null, HpPicture::getHpId, hospital.getId());//获取了图片名称
            List<HpPicture> hpPictures = hpPictureMapper.selectList(wrapper);
            if (!hpPictures.isEmpty()) {
                hospital.setImage(hpPictures.get(0).getPathImage());
            }

        }
        return PageUtil.toPage(all);
    }

    @Override
    public List<Hospital> queryAll(HospitalQueryCriteria criteria) {
        return hospitalMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Hospital resources) {
        convertCode(resources);
        save(resources);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Hospital resources) {
        Hospital hospital = getById(resources.getId());
        hospital.copy(resources);
        convertCode(hospital);
        saveOrUpdate(hospital);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Long> ids) {
        removeBatchByIds(ids);
        LambdaQueryWrapper<HpPicture> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(HpPicture::getHpId, ids);
        List<HpPicture> hpPictures = hpPictureMapper.selectList(wrapper);
        for (HpPicture hpPicture : hpPictures) {
            hpPicture.setStatus(0);
            hpPictureMapper.updateById(hpPicture);
        }
    }

    @Override
    public void download(List<Hospital> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Hospital hospital : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put(" position", hospital.getPosition());
            map.put(" category", hospital.getCategory());
            map.put(" areaCode", hospital.getAreaCode());
            map.put(" mnName", hospital.getMnName());
            map.put(" mnNameCode", hospital.getMnNameCode());
            map.put(" zhName", hospital.getZhName());
            map.put(" mnIntro", hospital.getMnIntro());
            map.put(" mnIntroCode", hospital.getMnIntroCode());
            map.put(" zhIntro", hospital.getZhIntro());
            map.put(" mnLocation", hospital.getMnLocation());
            map.put(" mnLocationCode", hospital.getMnLocationCode());
            map.put(" zhLocation", hospital.getZhLocation());
            map.put(" number", hospital.getNumber());
            map.put(" information", hospital.getInformation());
            map.put(" mnLeader", hospital.getMnLeader());
            map.put(" mnLeaderCode", hospital.getMnLeaderCode());
            map.put(" zhLeader", hospital.getZhLeader());
            map.put(" createBy", hospital.getCreateBy());
            map.put(" createTime", hospital.getCreateTime());
            map.put(" updateBy", hospital.getUpdateBy());
            map.put(" updateTime", hospital.getUpdateTime());
            map.put(" remark", hospital.getRemark());
            map.put(" status", hospital.getStatus());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public String uploadOrUpdate(MultipartFile file, HttpServletRequest request, Long hpId) {
        File filee = new File(path + "/upload");
        if (!filee.exists()) {//不存在
            filee.mkdirs();
        }
        String filename = file.getOriginalFilename();//获取文件名称带后缀名
        String uid = UUID.randomUUID().toString();//生成32为uuid值
        String suffix = filename.substring(filename.lastIndexOf(".")); //切割获取.后面的jpg
        String newFile = uid + suffix;//拼接新的文件名称
        File file1 = new File(filee + "/" + newFile);
        try {
            file.transferTo(file1);
        } catch (IOException e) {
            e.printStackTrace();
        }

        LambdaQueryWrapper<HpPicture> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(hpId != null, HpPicture::getHpId, hpId).eq(HpPicture::getStatus, 1);
        HpPicture picture = hpPictureMapper.selectOne(wrapper);
        if (picture == null) {
            //新增
            HpPicture hpPicture = new HpPicture();
            hpPicture.setHpId(hpId);
            hpPicture.setPathImage("/upload/" + newFile);
            hpPicture.setStatus(1);
            hpPictureMapper.insert(hpPicture);
        } else {
            //修改
            picture.setPathImage("/upload/" + newFile);
            picture.setStatus(1);
            hpPictureMapper.updateById(picture);
        }
        return newFile;
    }

    @Override
    public List<Hospital> getNameAndId() {
        LambdaQueryWrapper<Hospital> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Hospital::getStatus, 1);
        return hospitalMapper.selectList(wrapper);
    }

    @Override
    public List<Hospital> getByName(String zhName) {
        String replaceAll = IntermediateCodeUtils.mn2Code(zhName).replaceAll("-", " -");
        LambdaQueryWrapper<Hospital> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Hospital::getZhName, zhName).or().like(Hospital::getMnNameCode, replaceAll);
        List<Hospital> list = hospitalMapper.selectList(wrapper);
        for (Hospital hospital : list) {
            LambdaQueryWrapper<HpPicture> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(HpPicture::getHpId, hospital.getId()).eq(HpPicture::getStatus, 1);
            HpPicture hpPicture = hpPictureMapper.selectOne(wrapper1);
            if (hpPicture != null && hpPicture.getPathImage() != null) hospital.setImage(hpPicture.getPathImage());
        }
        return list;
    }


    private void convertCode(Hospital resources) {
        resources.setMnNameCode(IntermediateCodeUtils.mn2Code(resources.getMnName()).replaceAll("-", " -"));
        resources.setMnIntroCode(IntermediateCodeUtils.mn2Code(resources.getMnIntro()).replaceAll("-", " -"));
        resources.setMnLocationCode(IntermediateCodeUtils.mn2Code(resources.getMnLocation()).replaceAll("-", " -"));
        resources.setMnLeaderCode(IntermediateCodeUtils.mn2Code(resources.getMnLeader()).replaceAll("-", " -"));
    }
}
